import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
console.log(process.env.VUE_APP_BASE_API,'VUE_APP_BASE_API')

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    console.log(config.headers.platform)
    config.headers['platform'] = "WEB"
    // 金寓接口 需要切换baseURL
    if (config.jy) config.baseURL = '/api'
    const token = getToken()
    if (token) {
      if (config.jy) {
        config.headers['Authorization'] = token
      } else {
        config.headers['token'] = token
      }
    }
    // 将人员最大的权限放在headers中
    if (sessionStorage.getItem('loginUserinfo')&& JSON.parse(sessionStorage.getItem('loginUserinfo')).permission) {
      let permission = JSON.parse(sessionStorage.getItem('loginUserinfo')).permission;
      console.log(permission,'permissionpermission');
      let lastPermission;
      if (permission.length) {
        if (permission.indexOf('common') > -1) {
          lastPermission = 'common';
        }
        if (permission.indexOf('admin') > -1) {
          lastPermission = 'admin';
        }
        if (permission.indexOf('superAdmin') > -1) {
          lastPermission = 'superAdmin';
        }
        config.headers['permission'] = lastPermission;
      };
    }
    return config
  },
  error => {
    console.error(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 0) {
      if (res.code === 9999) {
        // 弹框提示 重新登录
        return MessageBox.confirm('登录信息过期，请重新登录', '请重新登录', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('admin/resetToken').then(() => {
            location.reload()
          })
        })
      } else {
        Message({
          message: res.message || res.msg || 'Error1',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(res.message || res.msg || 'Error2')
      }
    } else {
      if (response.config.jy) return res
      return res.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
